package com.jt.service;

import com.jt.mapper.ItemCatMapper;
import com.jt.pojo.ItemCat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 金帮嘉诚 @date 2021-08-14 星期六 17:19
 */
@Service
public class ItemCatServiceImpl implements ItemCatService {
    @Autowired
    private ItemCatMapper itemCatMapper;

    /**
     * @param level 1只查询1级商品分类 2查询1级和2级 3查询1\2\3级
     * @return 优化策略 尽量少查数据库
     */
    @Override
    public List<ItemCat> getItemCatList(Integer level) {
        Map<Integer, List<ItemCat>> map = getMap();
        if (level.equals(1)) {
            return map.get(0);
        }
        if (level.equals(2)) {
            return getLevel2List(map);
        }
        return getLevel3List(map);
    }

    //获取1\2\3级菜单
    public List<ItemCat> getLevel3List(Map<Integer, List<ItemCat>> map) {
        List<ItemCat> oneList = getLevel2List(map);
        for (ItemCat oneItemCat : oneList
        ) {
            List<ItemCat> twoList = oneItemCat.getChildren();
            //先判断不为空 再判断长度不为0
            if (twoList == null || twoList.size() == 0) {
                continue;
            }

            //放入children
            for (ItemCat twoItemCat : twoList
            ) {
                List<ItemCat> threeList = map.get(twoItemCat.getId());
                twoItemCat.setChildren(threeList);
            }
        }
        return oneList;
    }

    //获取1/2级菜单信息
    public List<ItemCat> getLevel2List(Map<Integer, List<ItemCat>> map) {
        //先获取一级菜单
        List<ItemCat> oneList = map.get(0);
        //将二级菜单装入一级菜单
        for (ItemCat oneItemCat : oneList
        ) {
            //根据1级 查对应的2级:   1级id=2级父id
            List<ItemCat> twoList = map.get(oneItemCat.getId());
            oneItemCat.setChildren(twoList);
        }
        return oneList;
    }

    //设计:将所有父id和子List的对应关系 封装在一个map中
    //之后操作map即可获得各级菜单 减少查询数据库的次数
    public Map<Integer, List<ItemCat>> getMap() {
        //查询所有记录
        List<ItemCat> itemCatList = itemCatMapper.selectList(null);
        //将包含所有父子关系
        Map<Integer, List<ItemCat>> map = new HashMap<>();
        //将关系封装进map
        for (ItemCat i : itemCatList
        ) {
            //逻辑:
            // 如果
            // 1.key在map中 再value中追加当前项
            // 2.key不在map中 新建List 将当前项添加 再把List加入map的value
            int key = i.getParentId();

            if (map.containsKey(key)) {
                List<ItemCat> childrenList = map.get(key);
                childrenList.add(i);
            } else {
                List<ItemCat> childrenList = new ArrayList<>();
                childrenList.add(i);
                map.put(key, childrenList);
            }
        }
        return map;
    }
    //
}
